package com.dede.monochromatism.db

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import org.jetbrains.anko.db.*

/**
 * @author hsh
 * @date 2017/9/19 9:34.
 * @doc
 */
class PackageDatabaseOpenHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "Package", null, 1) {

    companion object {
        val OPEN_TABLE = "open"
        val IGNORE_TABLE = "ignore"
        val packageName = "packageName"
        val name = "name"
        private var instance: PackageDatabaseOpenHelper? = null

        @Synchronized
        fun getInstance(ctx: Context): PackageDatabaseOpenHelper {
            if (instance == null) {
                instance = PackageDatabaseOpenHelper(ctx.applicationContext)
            }
            return instance!!
        }
    }

    override fun onCreate(db: SQLiteDatabase) {
        //打开表
        db.createTable(
                OPEN_TABLE, true,
                "_id" to INTEGER + PRIMARY_KEY,
                packageName to TEXT,
                name to TEXT,
                "date" to SqlTimeType("TIMESTAMP NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f','now','localtime'))")
        )

        //忽略表
        db.createTable(
                IGNORE_TABLE, true,
                "_id" to INTEGER + PRIMARY_KEY,
                packageName to TEXT,
                name to TEXT,
                "date" to SqlTimeType("TIMESTAMP NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f','now','localtime'))")
        )
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
    }

    private class SqlTimeType(override val name: String) : SqlType {

        override fun render(): String {
            return name
        }

        override fun plus(m: SqlTypeModifier): SqlType {
            return SqlTimeType(name)
        }

    }
}

val Context.database: PackageDatabaseOpenHelper
    get() = PackageDatabaseOpenHelper.getInstance(applicationContext)
val openTable: String get() = PackageDatabaseOpenHelper.OPEN_TABLE
val ignoreTable: String get() = PackageDatabaseOpenHelper.IGNORE_TABLE

val packageNameKey: String get() = PackageDatabaseOpenHelper.packageName
val nameKey: String get() = PackageDatabaseOpenHelper.name